

var HTTP = (function() {

    function require(url) {
        return new Promise((resolve, reject) => {
            var head = document.head || (document.getElementsByTagName("head")[0] || document.documentElement);
            var script = document.createElement("script");
            script.onload = () => {
                resolve();
            };
            script.onerror = () => {
                reject();
            };
            script.async = true;
            script.src = url;
            head.appendChild(script);
        });
    }


    function isAndroid() {
        return /(Android)/i.test(navigator.userAgent);
    }


    let axiosReadyState = false;
    let axiosLoading = false;
    let jsBridgeLoaded = false;
    if (isAndroid())
    {
        window.onJsBridgeReady = function () {
            jsBridgeLoaded = true;
        }
    }


    return {
        async setHeaders(headers) {
            if (jsBridgeLoaded && headers) {
                JsBridge.HTTP.setHeaders(headers);
            }
            else {

                if (!axiosReadyState)
                {
                    if (axiosLoading) {
                        await new Promise((resolve) => {
                            const i = setInterval(() => {
                                if (axiosReadyState)
                                {
                                    clearInterval(i);
                                    resolve();
                                }
                            }, 500);
                        });
                    } else {
                        try {
                            axiosLoading = true;
                            await require("/js/third/axios.min.js");
                            axiosReadyState = true;
                        } catch (e) {
                            throw e;
                        }
                    }
                }

                const keys = Object.keys(headers);
                keys.forEach(k => {
                    axios.defaults.headers.common[k] = headers[k];
                });
            }
        },

        async request(options) {

            const axiosRequest = async function() {

                // 等待 axios 加载完成
                if (!axiosReadyState)
                {
                    if (axiosLoading) {
                        await new Promise((resolve) => {
                            const i = setInterval(() => {
                                if (axiosReadyState)
                                {
                                    clearInterval(i);
                                    resolve();
                                }
                            }, 500);
                        });
                    } else {
                        try {
                            axiosLoading = true;
                            await require("/js/third/axios.min.js");
                            axiosReadyState = true;
                        } catch (e) {
                            throw e;
                        }
                    }
                }

                try {
                    return await axios(options);                
                } catch (e) {
                    throw e;
                }
            };
            const okHTTPRequest = async function() {
                // 等待 JSBridge 加载完成
                if (!jsBridgeLoaded)
                {
                    await new Promise((resolve) => {
                        window.onJsBridgeReady = function () {
                            jsBridgeLoaded = true;
                            resolve();
                        }
                    });
                }
                
                if (options.header)
                    JsBridge.HTTP.setHeaders(options.header);
                if (options.headers)
                    JsBridge.HTTP.setHeaders(options.headers);
                
                try {
                    return await new Promise((resolve, reject) => {
                        options.success = function(result) {
                            let finalResult = null;
                            try {
                                finalResult = JSON.parse(result);
                            } catch (e) {
                                console.error(e);
                                finalResult = result;
                            }
                            const response = {
                                data: finalResult
                            };
                            resolve(response);
                        };
                        options.failed = function(e) {
                            reject(e);
                        };
                        if (!options.method || options.method === "GET" || options.method === "get") {
                            if (options.data && Object.keys(options.data).length === 0)
                                options.data = undefined;
                            JsBridge.HTTP.ajaxForm(options);
                        }
                        else {
                            JsBridge.HTTP.ajaxJSON(options);
                        }
                    });
                } catch (e) {
                    throw e;
                }
            };


            // Android APP
            if (isAndroid() && options.url.includes("http"))
            {
                try {
                    return await okHTTPRequest();
                } catch (e) {
                    throw e;
                }
            }

            try {
                return await axiosRequest();
            } catch (e) {
                throw e;
            }
        }
    }
})();


